import { saveBlogApi } from '@/api/blog';
import { BLOG_STATUS } from '@/constants/common/blog-status';
import { useBlogStore } from '@/store/modules/blog';
import { htmlToMarkdown, markdownToHtml } from '@/utils/markdown';
import { ElMessage } from 'element-plus';
import { computed, onMounted, onUnmounted, ref } from 'vue';

/**
 * 沉浸式编辑器组合函数
 * @description 提供沉浸式编辑体验的核心功能
 */
export const useImmersiveEditor = () => {
  const blogStore = useBlogStore();
  const editorRef = ref();

  // 编辑器内容
  const content = computed({
    get: () => blogStore.blogInfo.blogContent || '',
    set: (value: string) => {
      blogStore.updateContent(value);
    }
  });

  // 自动保存定时器
  let autoSaveTimer: NodeJS.Timeout | null = null;

  // 检查是否真的需要保存（使用 store 的智能检测）
  const needsSaving = computed(() => blogStore.needsAutoSave() && blogStore.editorState.autoSave);

  // 开始自动保存
  const startAutoSave = () => {
    if (autoSaveTimer) clearInterval(autoSaveTimer);

    autoSaveTimer = setInterval(() => {
      if (needsSaving.value) {
        saveDraft();
      }
    }, blogStore.editorState.autoSaveInterval);
  };

  // 停止自动保存
  const stopAutoSave = () => {
    if (autoSaveTimer) {
      clearInterval(autoSaveTimer);
      autoSaveTimer = null;
    }
  };

  // 保存草稿
  const saveDraft = async () => {
    // 移除 hasUnsavedChanges 检查，允许用户手动保存
    try {
      blogStore.updateEditorState({ isLoading: true });

      const response = await saveBlogApi({
        ...blogStore.blogInfo,
        blogStatus: BLOG_STATUS.DRAFT
      });

      // 后端会根据blogId判断是新建还是更新
      // 如果是新建操作且返回了新的blogId，更新本地存储
      if (response.data?.blogId && !blogStore.blogInfo.blogId) {
        blogStore.setBlogInfo(
          {
            ...blogStore.blogInfo,
            blogId: response.data.blogId
          },
          true
        ); // 使用 isInitialLoad=true

        // 新建文章且有 collectionId 时，关联合集
        if (blogStore.blogInfo.collectionId) {
          try {
            await blogStore.associateBlogToCollection(
              response.data.blogId,
              blogStore.blogInfo.collectionId
            );
            ElMessage.success('保存成功，文章已添加到合集');
          } catch (associateError) {
            console.error('关联合集失败:', associateError);
            ElMessage.warning('文章已保存，但添加到合集失败');
          }
        } else {
          ElMessage.success('保存成功');
        }
      } else {
        // 更新现有文章，检查是否需要重新关联合集
        const currentBlogId = blogStore.blogInfo.blogId;
        const currentCollectionId = blogStore.blogInfo.collectionId;

        if (currentBlogId && currentCollectionId) {
          try {
            await blogStore.associateBlogToCollection(currentBlogId, currentCollectionId);
            ElMessage.success('保存成功，文章已更新并添加到合集');
          } catch (associateError) {
            console.error('关联合集失败:', associateError);
            ElMessage.warning('文章已保存，但添加到合集失败');
          }
        } else {
          ElMessage.success('保存成功');
        }
      }

      blogStore.markAsSaved();
    } catch (error) {
      ElMessage.error('保存失败，请检查网络连接');
      console.error('保存失败:', error);
    } finally {
      blogStore.updateEditorState({ isLoading: false });
    }
  };

  // 切换全屏模式
  const toggleFullscreen = () => {
    const currentFullscreen = blogStore.editorState.isFullscreen;
    blogStore.updateEditorState({ isFullscreen: !currentFullscreen });

    if (!currentFullscreen) {
      // 进入全屏
      const elem = document.documentElement;
      if (elem.requestFullscreen) {
        elem.requestFullscreen();
      }
    } else {
      // 退出全屏
      if (document.exitFullscreen) {
        document.exitFullscreen();
      }
    }
  };

  // 切换专注模式
  const toggleFocusMode = () => {
    const currentFocusMode = blogStore.editorState.isFocusMode;
    blogStore.updateEditorState({
      isFocusMode: !currentFocusMode,
      sidebarCollapsed: !currentFocusMode // 专注模式时自动折叠侧边栏
    });
  };

  // 切换侧边栏
  const toggleSidebar = () => {
    const currentCollapsed = blogStore.editorState.sidebarCollapsed;
    blogStore.updateEditorState({ sidebarCollapsed: !currentCollapsed });
  };

  // 切换编辑器模式
  const switchEditorMode = (mode: 'markdown' | 'rich') => {
    const currentMode = blogStore.editorState.activeEditor;

    if (mode !== currentMode) {
      // 获取当前内容
      const currentContent = content.value;
      let convertedContent = currentContent;

      // 根据当前模式和目标模式转换内容
      if (mode === 'markdown' && currentMode === 'rich') {
        // 从富文本转换为Markdown
        convertedContent = htmlToMarkdown(currentContent);
      } else if (mode === 'rich' && currentMode === 'markdown') {
        // 从Markdown转换为富文本
        convertedContent = markdownToHtml(currentContent);
      }

      // 更新编辑器模式
      blogStore.updateEditorState({ activeEditor: mode });

      // 更新内容类型到store
      blogStore.updateContent(convertedContent, mode);
    }
  };

  // 快捷键处理
  const handleKeyboardShortcuts = (event: KeyboardEvent) => {
    // Ctrl/Cmd + S: 保存
    if ((event.ctrlKey || event.metaKey) && event.key === 's') {
      event.preventDefault();
      saveDraft();
    }

    // Ctrl/Cmd + F: 专注模式
    if ((event.ctrlKey || event.metaKey) && event.key === 'f') {
      event.preventDefault();
      toggleFocusMode();
    }

    // Ctrl/Cmd + E: 切换编辑器模式
    if ((event.ctrlKey || event.metaKey) && event.key === 'e') {
      event.preventDefault();
      const newMode = blogStore.editorState.activeEditor === 'markdown' ? 'rich' : 'markdown';
      switchEditorMode(newMode);
    }

    // Escape: 退出全屏或专注模式
    if (event.key === 'Escape') {
      if (blogStore.editorState.isFullscreen) {
        toggleFullscreen();
      }
      if (blogStore.editorState.isFocusMode) {
        toggleFocusMode();
      }
    }
  };

  // 编辑器创建回调
  const handleEditorCreated = (editor: Editor) => {
    editorRef.value = editor;

    // 设置编辑器配置
    editor.getConfig().placeholder = '开始你的创作...';
    editor.getConfig().autoFocus = true;
  };

  // 编辑器内容变化回调
  const handleEditorChange = (editor: Editor) => {
    const content = editor.getHtml();
    blogStore.updateContent(content);

    // 如果有未保存的更改，创建本地备份
    if (blogStore.editorState.hasUnsavedChanges) {
      blogStore.saveLocalBackup();
    }
  };

  // 粘贴处理
  const handlePaste = (editor: Editor, event: ClipboardEvent) => {
    const items = event.clipboardData?.items;

    // 处理图片粘贴
    if (items) {
      for (const item of items) {
        if (item.type.indexOf('image') !== -1) {
          const file = item.getAsFile();
          if (file) {
            // 这里可以调用图片上传API
            // const url = await uploadImage(file);
            // editor.insertNode(createImageNode(url));
            event.preventDefault();
            return false;
          }
        }
      }
    }

    return true;
  };

  // 检查是否有未保存的更改
  const checkUnsavedChanges = () => {
    if (blogStore.editorState.hasUnsavedChanges) {
      return confirm('您有未保存的更改，确定要离开吗？');
    }
    return true;
  };

  // 恢复本地备份
  const restoreLocalBackup = () => {
    const success = blogStore.restoreFromLocalBackup();
    if (success) {
      ElMessage.success('已恢复本地备份');
    } else {
      ElMessage.warning('没有找到本地备份');
    }
  };

  // 生命周期钩子
  onMounted(() => {
    // 监听键盘事件
    document.addEventListener('keydown', handleKeyboardShortcuts);

    // 开始自动保存
    startAutoSave();
  });

  onUnmounted(() => {
    // 清理事件监听
    document.removeEventListener('keydown', handleKeyboardShortcuts);

    // 停止自动保存
    stopAutoSave();

    // 不再自动保存草稿，由用户手动保存
  });

  // 监听全屏变化
  onMounted(() => {
    const handleFullscreenChange = () => {
      const isFullscreen = !!document.fullscreenElement;
      if (isFullscreen !== blogStore.editorState.isFullscreen) {
        blogStore.updateEditorState({ isFullscreen });
      }
    };

    document.addEventListener('fullscreenchange', handleFullscreenChange);

    onUnmounted(() => {
      document.removeEventListener('fullscreenchange', handleFullscreenChange);
    });
  });

  return {
    // 编辑器相关
    editorRef,
    content,

    // 状态
    editorState: blogStore.editorState,
    writingStats: blogStore.writingStats,

    // 方法
    toggleFullscreen,
    toggleFocusMode,
    toggleSidebar,
    switchEditorMode,
    saveDraft,
    restoreLocalBackup,
    checkUnsavedChanges,

    // 编辑器回调
    handleEditorCreated,
    handleEditorChange,
    handlePaste
  };
};
